<template>
  <div class="post-page" v-if="shop">
    <div class="post-nav" v-if="showNoticeBar" >
      正在访问 {{ shop.user.nickname }} 的种草推荐,切换到<span @click="onMyPost">我的种草推荐</span>
    </div>
    <div class="head-img">
      <img src="../../../static/images/post/header.png"/>
    </div>

    <div class="header" v-if="shop">
      <img class="avatar" :src="shop.user.avatar" alt=""/>
      <div class="info">
        <div class="title">{{shop.user.nickname}}&nbsp;的种草推荐</div>
        <span class="desc">{{shop.desc ? shop.desc : 'TA很懒，什么都没写~~'}}</span>
      </div>
    </div>

    <div class="post-section" v-if="posts">
      <div class="p-list" v-for="(item, index) in posts" :key="index" >
        <image :src="item.content[0].image + '?imageMogr2/auto-orient/thumbnail/640x/quality/75'" mode="widthFix" @click="onPostDetail(item)"/>
        <div class="detail" @click="onPostDetail(item)">
          <div class="title"> {{item.title}} </div>
          <rich-text :nodes="item.info.text"></rich-text>
        </div>
        <div class="ops">
          <div class="like"  v-if="!item.liked"  @click="setLikePost(item)">
            <van-icon name="like-o" class="like-icon"/>
            <span class="like-num">{{item.like_num || '赞一下'}}</span>
          </div>
            <div class="like liked" v-if="item.liked" @click="cancelPost(item)">
            <van-icon name="like" class="like-icon"/>
            <span class="like-num">{{item.like_num}}</span>
          </div>
          <span class="time">
            {{item.created_at}}
            <span class="block">发布</span>
          </span>
        </div>
        <div class="list" v-if="item.products&&item.products.length >0 ">
          <div class="item" v-for="(pro, idx) in item.products" :key="idx" @click="toProDetail(pro.id)">
            <img class="pic" :src="pro.image + '?imageView2/1/w/120/h/120/q/75'"/>
            <div class="content">
              <div class="title">{{pro.title}} </div>
              <div class="price">￥{{pro.price}} </div>
            </div>
          </div>
        </div>
      </div>
    </div>
       <block v-if="!posts">
        <span class="empty-title">未开通种草</span>
      </block>
      <div class="back" >
        <van-row>
          <van-col span="10" offset="1">
            <div @click="onContact">
               <van-icon name="qr" class="like-icon"/>
                <span class="title">联系TA</span>
            </div>
          </van-col>
          <van-col span="2" style="color:#ddd">|</van-col>
          <van-col span="10"> 
            <div @click="toHome">
              <van-icon name="wap-home" class="like-icon" />
              <span class="title">返回首页</span>
            </div>
          </van-col>
        </van-row>
      </div>
    <page-footer/>
    <van-toast id="van-toast"/>
    <van-dialog id="van-dialog"/>
  </div>
</template>
<script>
import * as PostAction from '@/api/post'
import * as ShopAction from '@/api/shop'
import { mapState } from 'vuex'
import Toast from 'vant-weapp/dist/toast/toast'
import Dialog from 'vant-weapp/dist/dialog/dialog'
import Utils from '@/utils'
export default {
  data () {
    return {
      posts: null,
      shop: null,
      page: 1,
      finished: false
    }
  },
  computed: {
    ...mapState(['shop_name']),
    ...mapState(['me']),
    showNoticeBar () {
      if (!this.me) return false
      if (this.me.l_1 === 1 && this.me.invite_code !== this.shop_name) {
        return true
      }
      return false
    }
  },
  onPullDownRefresh () {
    this.page = 1
    this.finished = false
    if (this.shop_name) this.fetchShop(this.shop_name)
    wx.stopPullDownRefresh()
  },
  onLoad (query) {
    this.page = 1
    this.finished = false
    this.posts = null
    wx.showNavigationBarLoading()
    // scene存在,则优先判断
    if (query.scene) {
      let params = Utils.parseQuery(decodeURIComponent(query.scene))
      if (params.name) this.fetchShop(params.name)
      if (params.ic && params.ic.length === 6) wx.setStorageSync('__inviteCode', params.ic)
      return
    }
    if (query.code) wx.setStorageSync('__inviteCode', query.name)
    if (query.name) this.fetchShop(query.name)
  },
  onShareAppMessage (res) {
    return {
      title: this.shareTitle(),
      path: this.sharePath()
    }
  },
  onReachBottom () {
    this.page += 1
    wx.showNavigationBarLoading()
    this.fetchList()
  },
  methods: {
    toHome () {
      wx.switchTab({ url: '../home/index' })
    },
    onPostDetail (item) {
      wx.navigateTo({ url: '../post/detail?id=' + item.id + '&name=' + this.shop.name })
    },
    toProDetail (id) {
      wx.navigateTo({ url: '../product/detail?id=' + id })
    },
    onMyPost () {
      wx.showNavigationBarLoading()
      this.$store.commit('set_shop_name', this.me.invite_code)
      this.fetchShop(this.me.invite_code)
    },
    shareTitle () {
      if (!this.shop) return
      if (!this.me) return `美控家向您推荐种草相关`
      if (this.me) return `${this.me.nickname}向您推荐${this.shop.user.nickname}的种草`
    },
    sharePath () {
      if (!this.shop) return
      let url = '/pages/shop/index?name=' + this.shop.name
      let code = ''
      if (this.me && this.me.invite_code) {
        code = this.me.invite_code
      } else {
        code = this.shop.name
      }
      url = url + '&code=' + code
      return url
    },
    toLogin () {
      Dialog.confirm({
        title: '美控家',
        message: '您还没有登录，是否现在前往登录'
      }).then(() => {
        wx.redirectTo({ url: '/pages/auth/login-index?target=posts' })
      }).catch(() => {})
    },
    setLikePost (item) {
      if (!this.me) {
        this.toLogin()
        return
      }
      PostAction.likePost(item.id)
        .then(data => {
          this.$set(item, 'liked', true)
          this.$set(item, 'like_num', item.like_num + 1)
        })
        .catch(err => Toast(err.msg))
    },
    cancelPost (item) {
      if (!this.me) {
        this.toLogin()
        return
      }
      PostAction.cancelPost(item.id)
        .then(data => {
          this.$set(item, 'liked', false)
          this.$set(item, 'like_num', item.like_num - 1)
        })
        .catch(err => Toast(err.msg))
    },
    onContact () {
      if (!this.shop.qr_code) {
        Toast('他没有二维码')
        return
      }
      wx.previewImage({
        urls: [this.shop.qr_code + '?imageMogr2/auto-orient/thumbnail/640x/quality/75']
      })
    },
    fetchShop (name) {
      name = name.replace(/\s+/g, '')
      ShopAction.show(name).then(data => {
        this.shop = data
        this.$store.commit('set_shop_name', data.name)
        if (this.shop.version === 'v2') {
          this.posts = []
          this.fetchList()
        } else {
          wx.hideNavigationBarLoading()
        }
      }).catch(err => {
        wx.hideNavigationBarLoading()
        console.log(err)
      })
    },
    fetchList () {
      if (this.finished) {
        wx.hideNavigationBarLoading()
        return false
      }
      PostAction.fetchList({shop_name: this.shop.name, page: this.page})
        .then(data => {
          if (data.data.length > 0) {
            let list = data.data.map(val => {
              val.created_at = Utils.getDateDiffCountdown(val.created_at)
              val.info = val.content.find(el => { if (el.text) return el })
              return val
            })
            this.posts = this.posts.concat(list)
          } else {
            this.finished = true
          }
          wx.hideNavigationBarLoading()
        })
        .catch(err => {
          console.log(err)
          wx.hideNavigationBarLoading()
        })
    }
  }
}
</script>

<style lang="less" scoped>
  .post-page {
    background: #F9F9F9;
    padding-bottom: 120rpx;
  }
  .back {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    color: #6A6A6A;
    background: #FAFAFA;
    padding:15px 0;
    font-size: 30rpx;
    text-align: center;
    .like-icon {
      vertical-align:middle;
      font-size:15px;
    }
    .title {
      vertical-align:top;
      font-size:14px;
      margin:0 5px;
    }
    .like {
      display: inline-block;
      padding: 0;
    }
  }
  .like-num {
      margin-left: 5px;
      vertical-align: baseline;
    }
  .like {
      padding: 10rpx 20rpx;
      padding-left: 0;
    }
    .like-icon {
      vertical-align: middle;
    }
    .liked {
      color: #e4668d;
    }
  .post-nav {
    background:#f5f5f5;
    color: #777;
    font-size:20rpx;
    padding:16rpx;
    text-align: center;
    span {
      color: #E6648C;
      margin-left: 20rpx;
    }
  }
  .head-img {
    image {
      width: 100%;
      height: 210rpx;
    }
  }
  .header{
    background:#ffff;
    position:absolute;
    padding:20rpx 30rpx;
    border-radius:10rpx;
    left:30rpx;
    right:30rpx;
    top:88rpx;
    z-index: 200;
  .avatar{
    width: 40px;
    height: 40px;
    display: block;
    border-radius: 50%;
    float: left;
    margin-right: 10px;
  }
  .title{
    font-size: 14px;
  }
  .desc{
    font-size: 12px;
    color: #666;
  }
}

  .post-section {
    position: relative;
    .p-list {
      margin:20rpx 30rpx;
      padding:30rpx;
      background:#fff;
      image {
        width: 100%;
      }
      .detail {
        color: #575757;
        font-size: 26rpx;
        .title {
        color: #000000;
        font-weight: 500;
          display: flex;
          justify-content: space-between;
          font-size: 30rpx;
          margin-bottom: 10rpx;
        }
      }
  
      .ops{
        margin: 20rpx 0;
        font-size: 24rpx;
        color: #666;
        display: flex;
        justify-items: center;
        justify-content: space-between;
        .time {
          padding: 10rpx;
          color: #535353;
          .block {
            color: #999;
          }
        }
      }
  
      .list {
        width: 100%;
        .item {
          display: flex;
          justify-content: space-between;
          height: 120rpx;
          background: #f5f5f5;
          margin-bottom: 10rpx;
          overflow: hidden;
          .pic {
            width:120rpx;
            height:120rpx;
          }
          .content {
            flex: 1;
            padding: 5rpx;
            height:120rpx;
            overflow: hidden;
            .title {
              font-size:23rpx;
              padding:10rpx;
              height:50rpx;
              overflow:hidden;
            }
            .price {
              font-size: 24rpx;
              color: #d76b81;
            }
          }
        }
      }
    }
  }
  .empty-title {
    width: 100%;
    line-height: 155rpx;
    font-size: 26rpx;
    color: #575757;
    text-align: center;
    display: block;
  }
  .bottom-bar {
    display: flex;
    justify-content: space-between;
  }

</style>
